<template>
  <div class="roles-page">
    <el-card>
      <template #header>
        <div class="page-header">
          <h3>角色管理</h3>
          <el-button type="primary" @click="showAddDialog">
            <el-icon><Plus /></el-icon>
            新增角色
          </el-button>
        </div>
      </template>

      <!-- 表格区域 -->
      <el-table :data="tableData" v-loading="loading" stripe>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="角色名称" width="150" />
        <el-table-column prop="code" label="角色编码" width="150" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="permissions" label="权限数量" width="120">
          <template #default="{ row }">
            <el-tag type="info">{{ row.permissions?.length || 0 }}个权限</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === '启用' ? 'success' : 'danger'">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="warning" size="small" @click="handlePermissions(row)">
              权限设置
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDelete(row)"
              :disabled="row.code === 'admin'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑角色对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="handleDialogClose"
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleRules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="roleForm.code" placeholder="请输入角色编码" />
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="roleForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入角色描述" 
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="roleForm.status">
            <el-radio label="启用">启用</el-radio>
            <el-radio label="禁用">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 权限设置对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      title="权限设置"
      width="600px"
    >
      <el-tree
        ref="permissionTreeRef"
        :data="permissionTree"
        :props="treeProps"
        show-checkbox
        node-key="id"
        :default-checked-keys="checkedPermissions"
        check-strictly
      />
      
      <template #footer>
        <el-button @click="permissionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSavePermissions" :loading="permissionLoading">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const permissionDialogVisible = ref(false)
const submitLoading = ref(false)
const permissionLoading = ref(false)
const roleFormRef = ref()
const permissionTreeRef = ref()

// 角色表单
const roleForm = reactive({
  id: null,
  name: '',
  code: '',
  description: '',
  status: '启用'
})

// 表单验证规则
const roleRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色编码', trigger: 'blur' }
  ]
}

// 表格数据
const tableData = ref([
  {
    id: 1,
    name: '系统管理员',
    code: 'admin',
    description: '拥有系统所有权限',
    status: '启用',
    permissions: ['user:view', 'user:create', 'user:edit', 'user:delete'],
    createTime: '2024-01-01 10:00:00'
  },
  {
    id: 2,
    name: '普通用户',
    code: 'user',
    description: '基础用户权限',
    status: '启用',
    permissions: ['user:view'],
    createTime: '2024-01-02 10:00:00'
  },
  {
    id: 3,
    name: '财务人员',
    code: 'finance',
    description: '财务相关权限',
    status: '启用',
    permissions: ['finance:view', 'finance:create', 'finance:edit'],
    createTime: '2024-01-03 10:00:00'
  }
])

// 权限树数据
const permissionTree = ref([
  {
    id: 'system',
    label: '系统管理',
    children: [
      { id: 'user:view', label: '用户查看' },
      { id: 'user:create', label: '用户创建' },
      { id: 'user:edit', label: '用户编辑' },
      { id: 'user:delete', label: '用户删除' },
      { id: 'role:view', label: '角色查看' },
      { id: 'role:create', label: '角色创建' },
      { id: 'role:edit', label: '角色编辑' },
      { id: 'role:delete', label: '角色删除' }
    ]
  },
  {
    id: 'inventory',
    label: '库存管理',
    children: [
      { id: 'inventory:view', label: '库存查看' },
      { id: 'inventory:create', label: '库存创建' },
      { id: 'inventory:edit', label: '库存编辑' },
      { id: 'inventory:delete', label: '库存删除' }
    ]
  },
  {
    id: 'sales',
    label: '销售管理',
    children: [
      { id: 'sales:view', label: '销售查看' },
      { id: 'sales:create', label: '销售创建' },
      { id: 'sales:edit', label: '销售编辑' },
      { id: 'sales:delete', label: '销售删除' }
    ]
  },
  {
    id: 'finance',
    label: '财务管理',
    children: [
      { id: 'finance:view', label: '财务查看' },
      { id: 'finance:create', label: '财务创建' },
      { id: 'finance:edit', label: '财务编辑' },
      { id: 'finance:delete', label: '财务删除' }
    ]
  }
])

const treeProps = {
  children: 'children',
  label: 'label'
}

const checkedPermissions = ref([])
const currentRole = ref(null)

// 计算属性
const isEdit = computed(() => !!roleForm.id)
const dialogTitle = computed(() => isEdit.value ? '编辑角色' : '新增角色')

// 方法
const loadData = () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
  }, 500)
}

const showAddDialog = () => {
  dialogVisible.value = true
  resetForm()
}

const handleEdit = (row) => {
  dialogVisible.value = true
  Object.assign(roleForm, { ...row })
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该角色吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  } catch {
    // 用户取消删除
  }
}

const handlePermissions = (row) => {
  currentRole.value = row
  checkedPermissions.value = row.permissions || []
  permissionDialogVisible.value = true
}

const handleSubmit = async () => {
  if (!roleFormRef.value) return

  try {
    await roleFormRef.value.validate()
    submitLoading.value = true

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))

    if (isEdit.value) {
      // 编辑角色
      const index = tableData.value.findIndex(item => item.id === roleForm.id)
      if (index > -1) {
        tableData.value[index] = { ...roleForm }
      }
      ElMessage.success('编辑成功')
    } else {
      // 新增角色
      const newRole = {
        ...roleForm,
        id: Date.now(),
        permissions: [],
        createTime: new Date().toLocaleString()
      }
      tableData.value.unshift(newRole)
      ElMessage.success('新增成功')
    }

    dialogVisible.value = false
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitLoading.value = false
  }
}

const handleSavePermissions = async () => {
  if (!currentRole.value) return

  permissionLoading.value = true
  
  try {
    const checkedKeys = permissionTreeRef.value.getCheckedKeys()
    const halfCheckedKeys = permissionTreeRef.value.getHalfCheckedKeys()
    const allPermissions = [...checkedKeys, ...halfCheckedKeys]

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))

    // 更新角色权限
    const index = tableData.value.findIndex(item => item.id === currentRole.value.id)
    if (index > -1) {
      tableData.value[index].permissions = allPermissions
    }

    ElMessage.success('权限设置成功')
    permissionDialogVisible.value = false
  } catch (error) {
    ElMessage.error('权限设置失败')
  } finally {
    permissionLoading.value = false
  }
}

const handleDialogClose = () => {
  resetForm()
}

const resetForm = () => {
  Object.assign(roleForm, {
    id: null,
    name: '',
    code: '',
    description: '',
    status: '启用'
  })
  roleFormRef.value?.clearValidate()
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.roles-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.page-header h3 {
  margin: 0;
  color: #303133;
}
</style>
